<template>
    <div class="inner-tree point-no-selected" style="height: 100vh;width: 100%;"
    >
        <treeZ
                ref="treeRef"
                :tree-data="treeData"
                :layout="layout"
                @click-angle="clickAngle($event)"
                @click-node-up="clickNodeUp"
                @click-node-info="clickNodeInfo"
        >
            <template v-slot:data_info>
                <div
                    @mousedown="startDrag"
                    @touchstart="startDrag1"
                    @touchmove="doDrag1"
                    @touchend="endDrag1"
                    @mousedown.stop @touchstart.stop
                    class="node-Info"
                    :style="{
                        display: nodeInfoWrap ? 'block':'none',
         top: top + 'px', left: left + 'px'}"
                >
                    <div class="ognz-li">
                        <span class="node-Info-close el-icon-close" @click="closeNodeInfo">X</span>

                        <div class="ognz-li-content">
                            <div class="ognz-li-image">
                                <img
                                    style="height:100%;width:100%"
                                    :src="getImageUrl(showNodeInfo?.pic)"
                                />
                            </div>
                            <div class="ognz-li-text" >
                                <div class="text-ellipsis-hidden">{{showNodeInfo?.id}}</div>
                            </div>

                        </div>
                        <div class="text-ellipsis-hidden line-clamp-3" style="width: 100%;max-height: 240px;padding: 0 10px 10px 10px">
                            {{showNodeInfo?.id}}
                        </div>
                    </div>
                </div>
            </template>

            <template v-slot="slotProps">
                <!--必须实现的函数点击  -->
                <div class="tree-node-style"
                     @click="(e) => handleClickNode(slotProps,e)"
                >
                    <img
                        style="width: 100%; height: 100%;border-radius: 5px"
                        :src="getImageUrl(slotProps.item.pic)"
                    >
                    <div class="tree-font" style="font-size: 18px;width: 130px" >{{slotProps.item.id}}</div>
                    <div>
                    </div>
                </div>
            </template>
        </treeZ>
    </div>
</template>

<script>


/**
 *
 *
 * -----------    全功能 （组件）
 *
 *
 * */
import treeZ  from "vue-tree-zw"
import 'vue-tree-zw/tree-z/tree-z.css';
import treeData from "../assets/json/treeData.json"



export default {
    name: "example1",
    components:{
        treeZ
    },
    mounted() {
        console.log('组件实例：', this.treeData);
        this.$refs.treeRef.initTree();

    },
    data(){
        return{
            treeData: treeData,

            /*树节点属性*/
            layout:{
                //默认节点属性
                defaultNodeStyle: {
                    width: 85,  //节点宽度
                    height: 85, //节点高度
                },
                //默认节点布局
                defaultNodeLayouts:{
                    nodeDistanceX: 50,  //节点左右 距离
                    nodeDistanceY: 55,  //节点上下 距离
                },
                //右键菜单栏
                rightMenuBar: true,
                searchInput: true,
                toolPanel: true
            },
            /*右键菜单数据*/
            pointRightData:{
                domData: null,
                domNode: null,
            },


            /*详情界面*/
            nodeInfoWrap: false,
            //点击查看详情
            showNodeInfo:{

            },


            /*详情面板移动*/
            /*移动*/
            dragging: false,
            startX: 0,
            startY: 0,
            top: 20,
            left: 20,
            startTime:0,
            startTouches: [],

            /*缩放*/
            scale: 0.76,
            zoomFactor: 0.03, // 每次缩放的增量
        }
    },
    methods:{
        getImageUrl(picPath) {
            return picPath ? require(`@/${picPath}`) : require('@/assets/img/logo.png');
        },
        //默认回填函数
        handleClickNode(slotProps,e){
            console.log("点击时触发",slotProps.item,e,e.target)
            this.pointRightData.domNode = slotProps.item;

            slotProps.clickNode({
                data: slotProps.item,
            });
        },

        //查询子节点
        clickAngle(e){
            console.log("clickAngle",e);

            e.children = [
                {
                    "id": "data_132_1",
                    "children": null
                },
                {
                    "id": "data_132_2",
                    "children": null
                },
                {
                    "id": "data_132_3",
                    "children": null
                },
            ];

            if(this.$refs.treeRef){
                this.$refs.treeRef.insertTreeNode(e.nodeId,e);
            }
        },

        //查询父节点
        clickNodeUp(){
            let data =  {
                "id": "data_123",
                "name": "data_123",
                children: null
            }
            this.$refs.treeRef.insertUpTreeNode(data);
        },
        clickNodeInfo(){
            console.log(this.pointRightData);
            //查询详情
            this.showNodeInfo = this.pointRightData.domNode;

            this.nodeInfoWrap = true;
        },


        closeNodeInfo(){
            this.nodeInfoWrap = false;
            this.showNodeInfo = {};
        },
        //跳转
        goOrganizationInfo(ogId){
            console.log("跳转页面",ogId)
        },


        /*点击拖拽开始*/
        startDrag(e) {

            // 如果正在选择文本，不触发拖拽

            // 兼容鼠标和触摸事件
            const point = e.touches ? e.touches[0] : e;
            this.startX = point.clientX;
            this.startY = point.clientY;
            this.startTime = Date.now();
            this.dragging = false;
            this.initialLeft = this.left;  // 保存初始位置
            this.initialTop = this.top;

            // 绑定事件处理函数（使用箭头函数保持this上下文）
            const handleMove = (e) => this.doDrag(e);
            const handleEnd = (e) => this.endDrag(e);

            // 存储事件处理函数以便后续移除
            this.moveHandler = handleMove;
            this.endHandler = handleEnd;

            // 添加事件监听
            document.addEventListener('mousemove', handleMove);
            document.addEventListener('mouseup', handleEnd);
            document.addEventListener('touchmove', handleMove, { passive: false });  // 阻止默认行为
            document.addEventListener('touchend', handleEnd);

            // 阻止事件冒泡和默认行为
            // 改进：只在非输入元素上阻止事件
            const target = e.target.tagName.toLowerCase();
            // 检查目标元素是否为输入相关元素
            const isInputElement = ['input', 'textarea', 'select', 'button'].includes(target);

            if (!isInputElement) {
                e.stopPropagation();
                if (e.preventDefault) e.preventDefault();
            }


        },

        /*点触移动*/
        doDrag(e) {
            // 兼容鼠标和触摸事件
            const point = e.touches ? e.touches[0] : e;

            // 计算位移
            const deltaX = point.clientX - this.startX;
            const deltaY = point.clientY - this.startY;

            // 判断是否达到拖拽阈值（5px）
            const dragThreshold = 5;
            if (!this.dragging) {
                if (Math.abs(deltaX) > dragThreshold || Math.abs(deltaY) > dragThreshold) {
                    this.dragging = true;  // 标记为拖拽状态
                } else {
                    return;  // 未达到阈值，不执行拖拽
                }
            }

            // 执行拖拽（使用初始位置计算，避免累积误差）
            this.left = this.initialLeft + deltaX;
            this.top = this.initialTop + deltaY;

            // 阻止触摸设备上的默认行为（如滚动）
            // 阻止事件冒泡和默认行为
            // 改进：只在非输入元素上阻止事件
            const target = e.target.tagName.toLowerCase();
            // 检查目标元素是否为输入相关元素
            const isInputElement = ['input', 'textarea', 'select', 'button'].includes(target);

            if (!isInputElement) {
                if (e.preventDefault) e.preventDefault();
            }
        },

        /*点触结束*/
        endDrag(e) {
            // 判断是否为点击（未触发拖拽且时间短于300ms）
            //const isClick = !this.dragging && (Date.now() - this.startTime < 300);
            // if (isClick) {
            //     this.handleClick(e);  // 触发点击处理
            // }

            // 重置状态并移除事件监听
            this.dragging = false;
            document.removeEventListener('mousemove', this.moveHandler);
            document.removeEventListener('mouseup', this.endHandler);
            document.removeEventListener('touchmove', this.moveHandler);
            document.removeEventListener('touchend', this.endHandler);

            // 清理引用
            this.moveHandler = null;
            this.endHandler = null;
        },


        startDrag1(e){
            console.log("startDrag1")


            this.dragging = true;
            this.startX = e.touches[0].clientX;
            this.startY = e.touches[0].clientY;

            this.startTouches = [...e.touches]; // 记录触点位置
        },
        doDrag1(e){
            if (this.dragging) {
                //一指拖拽
                if (e.touches.length === 1){
                    const deltaX = e.touches[0].clientX - this.startX;
                    const deltaY = e.touches[0].clientY - this.startY;

                    this.left += deltaX ;
                    this.top += deltaY;
                    this.startX = e.touches[0].clientX;
                    this.startY = e.touches[0].clientY;
                }
                //二指缩放
                if (e.touches.length === 2) { // 当两指同时移动时
                    const endTouches = [...e.touches];
                    const startDistance = this.getDistance(this.startTouches[0], this.startTouches[1]);
                    const endDistance = this.getDistance(endTouches[0], endTouches[1]);

                    const scaleDiff = endDistance / startDistance; // 计算缩放比例差
                    this.scale *= scaleDiff; // 更新缩放比例

                    this.startTouches = [...endTouches]; // 更新开始触点位置
                }



            }
        },
        /*触摸缩放*/
        getDistance(touch1, touch2) {
            const dx = touch1.pageX - touch2.pageX;
            const dy = touch1.pageY - touch2.pageY;
            return Math.sqrt(dx * dx + dy * dy);
        },
        /*点触结束*/
        endDrag1() {
            this.dragging = false;
        },


    }

}
</script>

<style scoped>


.el-icon-close:hover{
    background-color: teal;
    color: white; /* 可选：同时修改图标颜色，增强对比 */
}

.node-Info{
    border: 1px solid saddlebrown;
    position: absolute;
    left: 50px;
    top: 50px;
    display: flex;
    border-radius: 5px;
    width: 260px;
    min-height: 100px;
    z-index: 100;
}

.node-Info:active{
    cursor: grab;
}

.node-Info-close{
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 100;
    padding: 3px;
    cursor: pointer;
    border-radius: 5px;
    font-size: 20px;

}

.ognz-label{
    display: inline-block;
    border-radius: 5px;
    padding: 3px 7px;
    font-size: 11px;
    margin-left: 10px;
    margin-top: 3px;

}

.ognz-li{
    position: relative;
    background: wheat;
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-content: start;
    padding: 5px;
    border-radius: 5px;
    overflow: hidden;
}
.ognz-li>div{
    display: flex;
    padding: 10px;
    background-color: white;
}
.ognz-li-content{
    min-height: 65px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

}
.ognz-li-content>div:nth-child(2){
    flex: 1;
    text-align: left;
    margin-left: 10px;
}
.ognz-li-text>div:nth-child(1){
    font-size: 16px;
}
.ognz-li-text>div:nth-child(2){
    font-size: 12px;

}


.ognz-li-image{
    width: 60px;
    height: 60px;
    border-radius: 5px;
    overflow: hidden;

}
.ognz-li-text .ognz-label{
    background-color: rgba(220, 223, 230, 0.3);
    margin-left: 3px;
    margin-top: 3px;
}



.node-info-button{
    width: 80px;
    height: 30px;text-align: center;
    line-height: 30px;padding: 0;
}
</style>
